from flask import Flask, jsonify, request
from .controller import app_init
from .extension import app_init as extension_init

app = Flask(__name__)


@app.route('/')
def root():
    ret = ''
    for k in app.url_map.iter_rules():
        ret += '<li><h1>' + str(k) + '</h1></li>'
    return '<body><ul>' + ret + '</ul></body>'


@app.route('/init')
def init():
    from app.extension.database.sqlalchemy import sqla_db
    from app.model.store_model import StoreModel
    from app.model.image_model import ImageModel
    from app.model.product_model import ProductModel
    from app.model.category_model import CategoryModel
    from app.model.product_category_model import ProductCategoryModel
    # sqla_db.drop_all()
    sqla_db.create_all()
    return 'ok'

@app.before_first_request
def before_first_request():
    pass


@app.before_request
def before_request():
    if request.json and request.json.get('user_id'):
        return jsonify({'errcode': 4003, 'msg': '403 Forbidden!'}), 403


@app.errorhandler(500)
def errorhandler(e):
    print(e)
    return jsonify({'errcode': 5000, 'msg': 'internal server error!'}), 500


def create_app(config) -> Flask:
    app.config.from_object(config)
    app_init(app)
    extension_init(app)
    return app
